<script setup>
import { reactive, ref, onMounted } from 'vue';
import { page,deleteById } from "@/api/careRecord";
import { findById } from "@/api/elderInfo";

import { useRouter } from "vue-router";
import dayjs from 'dayjs'

const formatTime = (row, column, cellValue) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
}

const router = useRouter();
const queryPageParam = reactive({
  name: '',
  pageNo: 1,
  pageSize: 5
});

// 数据
const tableData = ref([]);
const total = ref(0);
// 在数据部分添加职位映射
const elderMap = ref({});

// 修改getElderName方法
const getElderName = async (elderlyId) => {
  if (!elderlyId) return '无名字';
  
  // 如果已经缓存过，直接返回
  if (elderMap.value[elderlyId]) {
    return elderMap.value[elderlyId];
  }
  
  try {
    const res = await findById(elderlyId);
    if (res.data && res.data.name) {
      elderMap.value[elderlyId] = res.data.name;
      return res.data.name;
    }
    return '未知姓名';
  } catch (error) {
    console.error('获取老人信息失败:', error);
    return '未知姓名';
  }
};
const handleQueryPage = async () => {
  try {
    const res = await page(queryPageParam);
    tableData.value = res.data.records;
    total.value = res.data.total;
    
    // 预加载所有老人姓名
    await Promise.all(
      tableData.value.map(async (item) => {
        if (item.elderlyId) { // 确保使用正确的字段名
          await getElderName(item.elderlyId);
        }
      })
    );
  } catch (error) {
    console.error('查询数据失败:', error);
  }
};
const genderMap = reactive({
  1: '男',
  0: '女'
});
// 修改每页数量的回调函数
const handleSizeChange = (sizeValue) => {
  queryPageParam.pageSize = sizeValue;
  handleQueryPage();
};

// 修改页码之后的回调函数
const handleCurrentChange = (currentValue) => {
  queryPageParam.pageNo = currentValue;
  handleQueryPage();
};

// 查看
const handleDetail = (id) => {
  router.push({
    path: '/careRecord/detail',
    query: { id }
  });
};

// 编辑
const handleEdit = (id) => {
  router.push({
    path: '/careRecord/save',
    query: { id }
  });
};

// 确认删除
const handleDeleteConfirm = (id) => {
  deleteById(id).then(() => {
    handleQueryPage(); // 删除成功后再次分页查询
  });
};

// 新增
const handleAdd = () => {
  router.push({
    path: '/careRecord/save'
  });
};

// Vue 挂载完成之后执行钩子函数
onMounted(() => {
  handleQueryPage();
  
});
// 定义状态枚举
const careType = {
  PENDING: { value: 1, label: '基础护理', type: 'info' },
  APPROVED: { value: 2, label: ' 康复护理', type: 'success' },
  REJECTED: { value: 3, label: '心理护理', type: 'danger' },
  OUTING: { value: 4, label: '医疗护理', type: 'warning' },
  RETURNED: { value: 5, label: '其他', type: '' }
}

// 获取状态信息的方法
const getStatusInfo = (statusValue) => {
  return Object.values(careType).find(item => item.value === statusValue) || { label: '未知状态', type: '' }
}

</script>

<template>
  <div class="care-record-container">
    <!-- 头部区域 -->
    <div class="header-section">
      <h2 class="header-title">
        <el-icon class="title-icon"><UserFilled /></el-icon>
        护理记录管理
      </h2>
      <div class="action-buttons">
        <el-input
          v-model="queryPageParam.name"
          placeholder="请输入老人姓名"
          class="search-input"
          clearable
          @clear="handleQueryPage"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" class="query-button" @click="handleQueryPage">
          <el-icon><Search /></el-icon>查询
        </el-button>
        <el-button type="success" class="add-button" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增记录
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="data-card" shadow="never">
      <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        highlight-current-row
        class="elegant-table"
        v-loading="loading"
      >
        <el-table-column prop="careId" label="记录编号" width="120" align="center" />
        <el-table-column prop="elderlyId" label="老人ID" width="120" align="center" />
        
        <el-table-column prop="careType" label="护理类型" width="180" align="center">
          <template #default="scope">
            <el-tag :type="getStatusInfo(scope.row.careType).type" class="status-tag">
              {{ getStatusInfo(scope.row.careType).label }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="老人姓名" width="150" align="center">
          <template #default="scope">
            <div class="elder-info">
              <el-avatar :size="36" class="elder-avatar">
                {{ elderMap[scope.row.elderlyId]?.charAt(0) || '长' }}
              </el-avatar>
              <span class="elder-name">
                {{ elderMap[scope.row.elderlyId] || '加载中...' }}
              </span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="careContent" label="护理内容" width="200" show-overflow-tooltip />
        <el-table-column prop="remark" label="备注" width="180" show-overflow-tooltip />
        
        <el-table-column prop="evaluation" label="护理评价" width="150" align="center">
          <template #default="scope">
            <el-rate
              v-model="scope.row.evaluation"
              disabled
              :max="5"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="careTime" label="护理时间" width="180" align="center" :formatter="formatTime" />
        
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                size="small"
                class="view-button"
                @click="handleDetail(scope.row.careId)"
              >
                <el-icon><View /></el-icon>查看
              </el-button>
              <el-button
                type="primary"
                size="small"
                class="edit-button"
                @click="handleEdit(scope.row.careId)"
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-popconfirm
                title="确定要删除这条记录吗？"
                @confirm="handleDeleteConfirm(scope.row.careId)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    class="delete-button"
                  >
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryPageParam.pageNo"
        v-model:page-size="queryPageParam.pageSize"
        :page-sizes="[5, 10, 20, 30]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>


<style scoped>
.care-record-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

/* 头部区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.title-icon {
  margin-right: 12px;
  color: #4a6bdf;
  font-size: 28px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 280px;
}

.search-input :deep(.el-input__inner) {
  height: 40px;
  border-radius: 8px;
  padding-left: 36px;
}

.query-button,
.add-button {
  height: 40px;
  padding: 0 20px;
  border-radius: 8px;
  font-weight: 500;
}

.add-button {
  background: linear-gradient(120deg, #67c23a 0%, #5daf34 100%);
  border: none;
}

/* 数据卡片 */
.data-card {
  border-radius: 12px;
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.elegant-table {
  --el-table-border-color: transparent;
  --el-table-header-bg-color: #f5f8ff;
}

.elegant-table :deep(th) {
  background-color: #f5f8ff;
  color: #4a6bdf;
  font-weight: 600;
  height: 56px;
}

.elegant-table :deep(td) {
  height: 60px;
  border-bottom: 1px solid #f0f4f8;
}

/* 老人信息 */
.elder-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.elder-avatar {
  background: linear-gradient(135deg, #4a6bdf 0%, #3a56c4 100%);
  color: white;
  font-weight: bold;
}

.elder-name {
  font-weight: 500;
}

/* 状态标签 */
.status-tag {
  padding: 6px 12px;
  border-radius: 16px;
  font-weight: 500;
  border: none;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.view-button,
.edit-button,
.delete-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 500;
}

.view-button {
  background: #e3f2fd;
  color: #2196f3;
}

.edit-button {
  background: #e8f5e9;
  color: #4caf50;
}

.delete-button {
  background: #ffebee;
  color: #f44336;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .action-buttons {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
  }
  
  .action-buttons .el-button {
    flex: 1;
  }
}
</style>
